<template>
	<view class="container" v-if="loading">
		<!-- 授权登录 -->
		<view class="goback" style="background: #f7f7f7;  color: #e4e7ed; border: none;">登录中..</view>
	</view>
</template>
<script>
	export default {
		components: {},
		data() {
			return {
				loading: false,
				successUrl: '',
				nowStamp: (new Date()).getMilliseconds(),
				url: getApp().globalData.url,
				queryExpireApi:"/wxlogin/hasout", 		//TODO 是否登录掉线
				queryAuthUrlApi:"/wxlogin/wxauthurl",  	//TODO 获取授权URL地址
				loginAuthParam:false, 					//TODO授权所需参数
				myPageData:null,
				currentStep:undefined,
			};
		}, 
		onShow() {
			console.log("【页面显示】onShow ");
			//1、首先判断是否微信内的浏览器
			let isWechatAuth = false; 
			//this.myPageData = this.parseRequestQuery();
			console.log("【页面显示】加载 isWechatAuth",isWechatAuth);
		},
		onLoad(options) {
			let myParam  = this.parseRequestQuery();
			this.myPageData = myParam;
			this.currentStep = localStorage.getItem("STEPINDEX");
			console.log("启动-onLoadPageFunc 动态参数param=>",this.myPageData);
			//TODO 保存微信授权回调的数据
			localStorage.removeItem("AUTH_CODE");
			localStorage.removeItem("AUTH_STATE");
			//localStorage.removeItem("AUTH_JUMPURL");
			if(null !== myParam.code && undefined !==myParam.code && ""!==myParam.code){
				localStorage.setItem("AUTH_CODE",myParam.code);
			}
			if(null !== myParam.state && undefined !==myParam.state && ""!==myParam.state){
				localStorage.setItem("AUTH_STATE",myParam.state);
			}
			if(null !== myParam.jpauthurl && undefined !==myParam.jpauthurl && ""!==myParam.jpauthurl){
				localStorage.setItem("AUTH_JUMPURL",myParam.jpauthurl);
			}
			//TODO 启动页面方法
			this.onLoadPageFunc(); 
			console.log("加载-onLoadPageFunc 完成");
		},
		methods: {
			onLoadPageFunc() {
				let _that = this;
				//2、用户登录身份检测(本地localStorage存一份数据:本地存储10分钟内有效);
				//_that.checkLocalStorageUser();
				
				console.log("加载-onLoadPageFunc，checkIsWxCallBack Time="+_that.nowStamp);
				_that.checkIsWxCallBack();
				//this.findWxAuthService();   //TODO 获取授权接口数据
				//TODO 表示已跳微信授权【currentStep=2】
				//是否达到授权回调数据
				console.log("加载-onLoadPageFunc，当前stepIndex=" + this.currentStep);
				setTimeout(() => {
					_that.queryAuthExpire(); 
				},1000);
			},
			
			//TODO  检测会员是否授权过期；
			async queryAuthExpire() {
				this.loading = true;
				let queryExpireApi=this.queryExpireApi;
				let mdString = this.myPageData.mdstr || "";
				let subParam = {"mdstr":mdString,"gIndex":this.myPageData.gIndex||0};
				localStorage.removeItem("STEPINDEX");
				localStorage.removeItem("AUTH_JUMPURL");
				localStorage.removeItem("authLoginParam");
				localStorage.removeItem("authJumpLoginUser");
				console.log("【queryAuthExpire】请求接口"+queryExpireApi,subParam);
				if(null===mdString || undefined===mdString|| ""===mdString){
					uni.showToast({ title:"数据不完整" ,duration:3000,"icon":'error',mask:true });
					return;
				}
				//3、本地没有就去服务器检测，并登录授权身份；
				this.$api.request({
					url: this.url + queryExpireApi,
					method: 'POST',
					data: subParam,
					success: res => {
						let resData = res.data || null;
						console.log("【queryAuthExpire】请求结果返回" ,resData);
						if (res.code == 200) {
							this.loading = true ;
							let validAuth = resData.validAuth || 0;	//TODO 是否在线【跳微信授权】
							let hasJumpUrl = resData.jumpUrl || "";
							let jumpH5Url = resData.h5PageUrl || "";
							//TODO 登录身份还在线
							if(null !==validAuth && validAuth==1 && hasJumpUrl){
								this.successUrl=hasJumpUrl; 
								localStorage.setItem("authJumpLoginUser",JSON.stringify(resData)); 
								this.loginAuthParam = false;
								console.log("【checkLocalStorageUser】跳转jump成功",hasJumpUrl);
								this.jumpPage(hasJumpUrl); //TODO 没过期，直接跳到H5页面去；
							}else{
								//TODO 需要授权登录
								this.loginAuthParam = {"hasAuth":0,"authUrl":resData.authUrl,"h5PageUrl":resData.h5PageUrl,"state":resData.authState };
								localStorage.setItem("authLoginParam",JSON.stringify(this.loginAuthParam));
								localStorage.setItem("STEPINDEX",1);
								
								//TODO页面跳转
								if(null !== jumpH5Url && undefined !== jumpH5Url && ""!==jumpH5Url){
									localStorage.setItem("AUTH_JUMPURL",jumpH5Url); 
								}
								//TODO 获取授权接口数据
								this.findWxAuthService();  
							}
						} else {
							this.$api.msg(res.msg);
							return;
						}
					}
				}); 
			},
			//3、获取授权接口
			async findWxAuthService() {
				let queryAuthApi=this.queryAuthUrlApi;
				let subParam =  this.loginAuthParam;
				if(!subParam){
					let authParamStr = localStorage.getItem("authLoginParam");
					subParam = authParamStr?JSON.parse(authParamStr):{};
				}
				uni.showToast({ title:"授权处理中..." });
				console.log("【findWxAuthService】获取参数loginAuthParam=>",subParam);
				this.$api.request({
					url: this.url + queryAuthApi,
					method: 'POST',
					data: subParam,
					success: res => {
						let resData = res.data || null;
						console.log("【findWxAuthService】请求接口"+queryAuthApi,resData);
						if (res.code == 200) {
							let authJumpUrl = resData.requestUrl || "";
							if(null !== authJumpUrl && ""!==authJumpUrl){
								localStorage.setItem("STEPINDEX",2);
								//TODO 跳转授权页面；
								console.log("【findWxAuthService】跳转授权地址 => ",authJumpUrl);
								this.jumpPage(authJumpUrl); 
							}else{
								this.$api.msg("获取数据错误，请重试");
							}
							return;
						} else {
							this.$api.msg(res.msg);
							return;
						}
					}
				}); 
			},
			//TODO 检测授权是否过期，
			checkLocalStorageUser(){
				let jumpLoginData = localStorage.getItem("authJumpLoginUser"); //TODO 本地储存的数据
				let loginAuth = jumpLoginData?JSON.parse(jumpLoginData):null;
				console.log("【checkLocalStorageUser】本地缓存跳转jump数据",loginAuth);
				let jumpSucUrl = loginAuth && loginAuth.jumpUrl || '';
				let jumpExpire = loginAuth && loginAuth.expire || 0;
				if(null !== loginAuth && jumpExpire > this.nowStamp && null !== jumpSucUrl && "" !== jumpSucUrl){
					//TODO 没过期，直接跳到H5页面去；
					console.log("【checkLocalStorageUser】跳转jump成功",jumpSucUrl);
					this.jumpPage(jumpSucUrl); 
				}
			},
			//TODO 是否为微信回调数据
			checkIsWxCallBack(){
				let wxCode = localStorage.getItem("AUTH_CODE");
				let wxState = localStorage.getItem("AUTH_STATE");
				let wxJumpUrl = localStorage.getItem("AUTH_JUMPURL");
				//TODO 验证数据值，
				if(wxCode && wxState && wxJumpUrl){
					let jumpSucUrl = wxJumpUrl +"?wxCode="+wxCode+"&wxState="+wxState;
					console.log("【checkIsWxCallBack】回调成功后的跳转jump地址：",jumpSucUrl);
					this.jumpPage(jumpSucUrl);
				}
				return ;
			},
			//TODO 请求参数解析值
			parseRequestQuery() {
				const search = new URLSearchParams(window.location.search);
				const res = {};
				search.forEach((value, key) => {
					let arr = res[key];
					if (arr === undefined) {
						arr = res[key] = value;
					} else if (Array.isArray(arr)) {
						arr.push(value);
					} else {
						res[key] = [arr, value];
					}
				});
				return res;
			},
			//TODO 跳转出去页面
			jumpPage(url){
				console.log("【jumpPage】跳转出去",url);
				window.location.href = url; 
				return ;
			}
		}
	};
</script>

<style lang="scss">
	page,.container{
		background: #fff;
		width: 100%;
		min-height: 100%; 
		text-align: center;
		position: relative;
	}
	.bg{
		width: 700upx;
		margin: 20upx auto;
		height: 1304upx;
	}
</style>